/* eslint-disable */
import Request from './request';
import {
	refreshToken
} from '@/api/login';
import indexConfig from '@/config/index.config';
import mHelper from '@/utils/helper';
import store from '@/store';
const http = new Request();

// request全局参数设置
http.setConfig(config => {
	/* 设置全局配置 */
	config.baseUrl = indexConfig.baseUrl; /* 根域名不同 */
	const systemInfo = uni.getSystemInfoSync();
	const systemInfoHeaders = {
		'device-name': systemInfo.brand, // 设备名称
		width: systemInfo.screenWidth, // 屏幕宽度
		height: systemInfo.screenHeight, // 屏幕高度
		os: systemInfo.platform, // 客户端平台
		'os-version': systemInfo.system // 操作系统版本
	};
	config.header = {
		...config.header,
		...systemInfoHeaders
	};
	return config;
});

let isRefreshing = false;
let requests = [];
http.interceptor.request(
	config => {
		/* 请求之前拦截器 */
		if (config.url.indexOf("merapi/") > -1) {
			var merchant = uni.getStorageSync('merchant')
			config.header['x-api-key'] = merchant ? merchant.access_token : '';
		}else if(config.url.indexOf("backapi/") > -1){
			//驻场端
			config.header['x-api-key'] = uni.getStorageSync(Config.cacheFix + 'residentAccessToken');
		}else {
			config.header['x-api-key'] = uni.getStorageSync('accessToken');
		}
		// 单商户
		//config.header['merchantId'] = indexConfig.merchantId || 1;
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 刷新refreshToken
async function handleRefreshToken(refresh_token) {
	const params = {};
	params.group = mHelper.platformGroupFilter();
	params.refresh_token = refresh_token;
	await http.post(refreshToken, params).then(async r => {
		store.commit('login', r.data);
		isRefreshing = false;
	});
}
async function wxCode(response) {
	console.log(response);
	const js_code = await new Promise((resolve, reject) => {
		// uni.login非异步，所以用Promise包装  
		uni.login({
			provider: 'weixin',
			success: async function(loginRes) {
				resolve(loginRes.code);
			},
			fail: err => {
				uni.setStorageSync(indexConfig.cacheFix + 'loging', false)
				reject(err);
			}
		});
	});
	console.log(js_code);
	return await refreshRuqest(js_code, response);
}
async function refreshRuqest(code, response) {
	var mes = {
		iv: '',
		rawData: '',
		encryptedData: '',
		signature: ''
	};
	const info = await new Promise((resolve, reject) => {
		//获取用户信息
		// wx.getUserInfo({
		// 	success: async function(res) {
		// 		mes.iv = res.iv,
		// 			mes.rawData = res.rawData,
		// 			mes.encryptedData = res.encryptedData,
		// 			mes.signature = res.signature;
		// 		resolve(mes);
		// 	}
		// })
		var mes = {
			iv: 1,
			rawData: 1,
			encryptedData: 1,
			signature: 1
		}
		resolve(mes);
	});
	var param = {
		code: code,
		...info
	};
	// #ifdef MP-WEIXIN
	param.group = 'wechatMp';
	// #endif
	// #ifdef H5
	param.group = 'wechat';
	// #endif

	var pid = uni.getStorageSync(indexConfig.cacheFix + 'pid');
	if (pid) {
		param.pid = pid;
	}
	var result = '';

	//用户端
	await http.post('api/canteen/v1/third-party/wechat-mp', param).then(async r => {
		uni.setStorageSync(indexConfig.cacheFix + 'loging', false)
		var openid = r.openid;
		if (openid) {
			uni.setStorageSync(indexConfig.cacheFix + 'openid',
				openid);
		};
		result = r;
	});

	return result;
}
http.interceptor.response(
	async response => {
			/* 请求之后拦截器 */
			switch (response.data.code) {
				case 200:
					return response.data;
				case 400:
					mHelper.toast('错误的请求');
					return Promise.reject(response.data.message);
					break;
				case 401:
					if (response.config.url.indexOf('merapi/') > -1) {
						uni.showModal({
							content: '请先登录',
							success: async e => {
								if (e.confirm) {
									uni.redirectTo({
										url:'/merchant/public/login',
									})
								}
							}
						})
						return response.data;
					}
					if (indexConfig.is_auto_auth == true) {

						var isLoging = uni.getStorageSync(indexConfig.cacheFix + 'loging');
						//
						var start = new Date().getTime();
						var end = '';
						var loginParam = {};
						var param = {
							start: start,
							end: end
						}
						loginParam = uni.getStorageSync(indexConfig.cacheFix + 'loginParam') && uni.getStorageSync(
							indexConfig
							.cacheFix + 'loginParam').start ? uni.getStorageSync(indexConfig.cacheFix +
							'loginParam') : param;
						loginParam.end = loginParam.start;
						// 更新缓存中的当前时间
						loginParam.start = start;
						uni.setStorageSync(indexConfig.cacheFix + 'loginParam', loginParam);

						var remainder = Math.abs(loginParam.end - loginParam.start) / 1000;
						if (remainder > 60) {
							isLoging = false;
							uni.setStorageSync(indexConfig.cacheFix + 'loginParam', loginParam);
						}
						//
						// #ifdef MP-WEIXIN

						if (!isLoging) {
							uni.setStorageSync(indexConfig.cacheFix + 'loging', true);
							// var result ={
							// 	code:200,
							// 	data:{
							// 		is_bind :0,
							// 		user_info:{
							// 			openid:''
							// 		}
							// 	}
							// };
							var result = await wxCode(response);
							console.log(result);
							if (result.code == 200) {
								if (result.data.is_bind != 1) {
									let currentPage=this.$mp.page.route
									uni.setStorageSync('backToPage',currentPage)
									uni.showModal({
										content: '请绑定您的手机号',
										success: async e => {
											if (e.confirm) {
												uni.redirectTo({
													url:'/pages/public/login?openid='+result.data.user_info.openid
												})
											}
										}
									})
									return;
								}
								store.commit('login', result.data.user_info);
								//执行需要重新请求的接口
								requests.forEach(cb => cb());
								requests = [];
								isRefreshing = false;
								var res = http.request(response.config);
								return res;

							}
						} else {
							return new Promise((resolve) => {
								// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
								requests.push(() => {
									resolve(http.request(response.config));
								})
							})
						}
						// #endif
						//自动授权
						// #ifdef H5
						if (!isLoging) {
							uni.setStorageSync(Config.cacheFix + 'loging', true);
							if (payment.isWechat()) {
								mHelper.setbBackToPage();
								var appid = Config.appid;
								var backToPage = uni.getStorageSync(Config.cacheFix + 'backToPage');
								backToPage = JSON.stringify(backToPage);
								var href = '';
								if (backToPage.indexOf('diancan/index/index') != -1) {
									href = Config.domain + "/pages/public/loging";
								} else {
									href = Config.domain + "/pages/public/loging";
								}
								window.location.href =
									`https://open.weixin.qq.com/connect/oauth2/authorize?
							appid=${appid}&
							redirect_uri=${href}&
							response_type=code&
							scope=snsapi_userinfo&
							state=STATE#wechat_redirect`;
							} else {
								uni.setStorageSync(Config.cacheFix + 'loging', false);
								mHelper.backToLogin();
								return response.data;
							}
						}
						// #endif
						//#ifdef APP-PLUS
						mHelper.backToLogin();
						//#endif

					} else {
						mHelper.backToLogin();
						return response.data;
					}
					break;
				case 405:
					mHelper.toast('当前操作不被允许');
					return Promise.reject(response.data.message);
				case 404:
					mHelper.toast(response.data.message);
					return Promise.reject(response.data.message);
				case 429:
					mHelper.toast('请求过多，先休息一下吧');
					return Promise.reject(response.data.message);
				case 500:
					mHelper.toast('服务器打瞌睡了');
					return Promise.reject(response.data.message);
				default:
					mHelper.toast(response.data.message);
					return Promise.reject(response.data.message);
			}
		},
		error => {
			return Promise.reject(error);
		}
);

export {
	http
};